const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager()
let speakWaveZoom = 1
let app =  getApp();
Page({
  data: {
    // 发送的新消息
    chatMyself:'',
    chat_list:[
      {is_chat_back:true,content:'今天天气多云转晴，气温下降，注意保暖~'},
    ],
    recordState:false,
    content:'',
    showVoiceCard:false,
    voiceValue:'',
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '药崽解答', //导航栏 中间的标题
      white: false, // 是就显示白的，不是就显示黑的。
      bgColor:'#B7EADE' // 加个背景 不加就是没有
    },
    // 导航头的高度
    height: app.globalData.height * 2 + 20
  },
  onLoad(){
    this.drawWave()

    this.initRecord()
  },
   //识别语音 -- 初始化
  initRecord: function () {
    const that = this;
    console.log('yes')
    // 有新的识别内容返回，则会调用此事件
    manager.onRecognize = function (res) {
      console.log(res)
    }
    // 正常开始录音识别时会调用此事件
    manager.onStart = function (res) {
      console.log("成功开始录音识别", res)
    }
    // 识别错误事件
    manager.onError = function (res) {
      console.error("error msg", res)
    }
    //识别结束事件
    manager.onStop = function (res) {
      console.log('语音内容 --> ' + res.result);
      that.setData({chatMyself:res.result})
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚，请重新说一遍！',
          showCancel: false,
          success: function (res) {}
        })
        return;
      }
    }
  },
  chatChange(e){
    this.setData({chatMyself:e.detail.value})
  },
  sendChatValue(){
    let chat_list = this.data.chat_list;
    let chatMyself = this.data.chatMyself;
    let that = this
    if(chatMyself != '') {
      chat_list.push({is_chat_back:false,content:chatMyself});
          this.setData({
            chat_list,
            chatMyself:''
          })
      setTimeout(
        function(){
          that.aiRequest(chatMyself)
        },500)
    }
    
  },

  // ai回复
  aiRequest(msg){
    let that = this
    let chat_list = this.data.chat_list;
    chat_list.push({is_chat_back:true,content:'',state:1});
    this.setData({chat_list})
    wx.request({
      url:'http://api.qingyunke.com/api.php',
      data:{
        key:'free',
        appid:0,
        msg:msg
      },
      success(res){
        let { result, content } = res.data;
        content = content.replace(/(\{br\})/g,'\n');
        chat_list[chat_list.length-1].state = 0;
        chat_list[chat_list.length-1].content = content;
        that.setData({chat_list})
      }
    })
  }, 
  startRecognize(){
    this.setData({recordState:true})
    manager.start({
      lang: 'zh_CN',// 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
    })
  },
  endRecognize(){
    this.setData({recordState:false})
    // 语音结束识别
    manager.stop();
  },
  onShow: function () {
    // 链接导航栏
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        // 当前页面的 tabBar 索引
        active: 0
      })
    }
  },
  

  /**
   * 绘制波浪线
   */
  drawWave () {
    let that = this
    var unit = 100,
      canvas, ctx, canvas2, ctx2,
      height, width, xAxis, yAxis,
      draw;
    /**
     * Init function.
     *
     * Initialize variables and begin the animation.
     */
    function init() {
      const query = wx.createSelectorQuery()
      query.select("#sineCanvas")
      .fields({ node: true, size: true })
      .exec(res=> {
        let canvas = res[0].node;
        let ctx = canvas.getContext('2d');
        that.setData({ctx})

        canvas.width  = res[0].width; //Canvasのwidthをウィンドウの幅に合わせる
        canvas.height = res[0].height;

        height        = canvas.height;
        width         = canvas.width;
        xAxis         = Math.floor(height/2);
        yAxis         = 0;
        draw();
      })
    }
    
    /**
     * Draw animation function.
     *
     * This function draws one frame of the animation, waits 20ms, and then calls
     * itself again.
     */
    function draw() {
      // clear canvas
      let ctx = that.data.ctx
      ctx.clearRect(0, 0, width, height);
    
      //波を描画
      // drawWave()の引数colorとして値が保存されている
      drawWave(ctx,'#000', .6, 1, 0);
      drawWave(ctx,'#000', .4, .8, 250);
      // drawWave(ctx,'#000', .2, .4, 100);
    
      // Update the time and draw again
      draw.seconds = draw.seconds + .014;
      draw.t = draw.seconds*Math.PI;
      setTimeout(draw,35);
    };
    
    draw.seconds = 0;
    draw.t = 0;
    
    /**
    * 波を描画
    * drawWave(颜色, 不透明度, 波浪的幅度zoom, 波浪开始的位置)
    */
    function drawWave(ctx,color, alpha, zoom, delay) {
      ctx.fillStyle = color;
      ctx.strokeStyle = color;
      ctx.globalAlpha = alpha;
      ctx.beginPath(); //start path
      // 波动时间
      drawSine(ctx,draw.t /  0.3, zoom, delay);
      ctx.stroke();
    }
    
    /**
     * Function to draw sine
     *
     * The sine curve is drawn in 10px segments starting at the origin.
     * drawSine(時間, 波浪的幅度, 波浪开始的位置)
     */
    function drawSine(ctx,t, zoom, delay) {
    
      // Set the initial x and y, starting at 0,0 and translating to the origin on
      // the canvas.
      var x = t; //时间是水平位置
      var y = Math.sin(x)/zoom;
      ctx.moveTo(yAxis, unit*y+xAxis); //开始位置
    
      // Loop to draw segments (按宽度绘制波浪)
      for (let i = yAxis; i <= width + 10; i += 10) {
        x = t+(-yAxis+i)/unit/zoom;
        y = Math.sin(x - delay)/6;
        ctx.lineTo(i, unit*y+xAxis);
      }
    }
    init();
    }
})